package com.greenova.projector.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.greenova.projector.entity.Person;
import com.greenova.projector.entity.Project;
import com.greenova.projector.model.PersonInputModel;
import com.greenova.projector.service.PersonService;
import com.greenova.projector.service.ProjectService;

@Controller
public class PersonController {

	@Autowired
	private PersonService personService;
	
	@Autowired
	private ProjectService projectService;
	
	
	@RequestMapping(value = "/addPerson", method=RequestMethod.GET)
	public ModelAndView addPerson(ModelAndView modelAndView) {
		modelAndView.addObject("personInputModel", new PersonInputModel());
		modelAndView.setViewName("create-person");
		return modelAndView;
	}
	
	@RequestMapping(value = "/savePerson", method=RequestMethod.POST)
	public ModelAndView savePerson(ModelAndView modelAndView, @ModelAttribute PersonInputModel personInputModel) {
		personService.addPerson(mapToPerson(personInputModel));
//		List<Person> persons = personService.listAllPersons();
//		modelAndView.addObject("persons", persons);
//		modelAndView.setViewName("list-of-persons");
		
		List<Project> projects = projectService.listAllProjects();
		modelAndView.addObject("projects", projects);
		modelAndView.setViewName("home");
		
		return modelAndView;
	}
	
	@RequestMapping(value = "/listPersons", method=RequestMethod.GET)
	public ModelAndView listOfPersons(ModelAndView modelAndView) {
		List<Person> persons = personService.listAllPersons();
		modelAndView.addObject("persons", persons);
		modelAndView.setViewName("list-of-persons");
		return modelAndView;
	}
	
	private Person mapToPerson(PersonInputModel personInputModel) {
		Person person = new Person();
		person.setFirstName(personInputModel.getFirstName());
		person.setLastName(personInputModel.getLastName());
		person.setPassword(personInputModel.getPassword());
		person.setUserName(personInputModel.getUserName());
		return person;
	}
}
